package cn.rqfund.etl.hsqldb;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Properties;

import org.hsqldb.server.Server;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * hsql 启动关闭类
 * 
 * @author dengrq dengrq@staff.tianya.cn
 * @date 2013-7-22
 */
public class HsqlActivator implements BundleActivator {

	Logger logger = LoggerFactory.getLogger(this.getClass());

	private int port = 9002;

	private String dbName = "testdb";

	private String dbPath = "data/hsqldb/";

	private static String driverClass = "org.hsqldb.jdbcDriver";

	private String server = "localhost";

	private String userName = "sa";

	private String password = "";

	private static String fileName = "file:/hsqldb.properties";

	@Override
	public void start(BundleContext context) throws Exception {

		initParam();
		Server server = new Server();

		server.setDatabaseName(0, dbName);
		server.setDatabasePath(0, dbPath + dbName);
		logger.debug(dbPath,dbName);

		if (port != -1)
			server.setPort(port);

		server.setSilent(true);
		server.setTrace(true);

		server.start();

		logger.info(" ============= hsqldb started...");
	}

	/**
	 * 初始化参数
	 * 
	 * @throws IOException
	 */
	private void initParam() {
		try {
			InputStream in = new URL(fileName).openStream();
			Properties prop = new Properties();
			prop.load(in);
			
			if (isNotBlank((String) prop.get("port"))) {
				port = Integer.valueOf((String) prop.get("port"));
			}

			if (isNotBlank((String) prop.get("dbName"))) {
				dbName = (String) prop.get("dbName");
			}

			if (isNotBlank((String) prop.get("dbPath"))) {
				dbPath = (String) prop.get("dbPath");
			}

			if (isNotBlank((String) prop.get("server"))) {
				server = (String) prop.get("server");
			}

			if (isNotBlank((String) prop.get("userName"))) {
				userName = (String) prop.get("userName");
			}

			if (isNotBlank((String) prop.get("password"))) {
				password = (String) prop.get("password");
			}
		} catch (Exception ex) {
			logger.error("读取配置文件出错.", ex.getMessage());
		}
	}

	private boolean isNotBlank(String str) {
		if (str != null && (!str.trim().equals(""))) {
			return true;
		}
		return false;
	}

	@Override
	public void stop(BundleContext context) throws Exception {
		logger.info(" ============= HsqlListener destroyed...");

		Connection conn = null;
		try {
			Class.forName(driverClass);
			StringBuffer jdbcUrl = new StringBuffer("jdbc:hsqldb:hsql://");
			jdbcUrl.append(server);
			jdbcUrl.append(":");
			jdbcUrl.append(port);
			jdbcUrl.append("/");
			jdbcUrl.append(dbName);
			conn = DriverManager.getConnection(jdbcUrl.toString(), userName,
					password);
			Statement stmt = conn.createStatement();

			stmt.executeUpdate("SHUTDOWN;");

			logger.info(" ============= hsqldb shutdown...");
		} catch (Exception e) {
			logger.error("=========== stop hsqldb error. ", e);
		}
	}

}
